package com.steamedfish.auctionitemserver.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.steamedfish.auctionitemserver.entiry.AuctionItem;
import com.steamedfish.auctionitemserver.entiry.AuctionItemImage;
import com.steamedfish.auctionitemserver.entiry.UserEntiry;
import com.steamedfish.auctionitemserver.mapper.AuctionItemImageMapper;
import com.steamedfish.auctionitemserver.mapper.AuctionItemMapper;
import com.steamedfish.auctionitemserver.model.AuctionItemModel;
import com.steamedfish.auctionitemserver.service.AuctionItemImageService;
import com.steamedfish.auctionitemserver.service.AuctionItemService;
import com.steamedfish.auctionitemserver.service.elasticsearch.ElasticSearchService;
import com.steamedfish.auctionitemserver.utils.ConvertUtils;
import com.steamedfish.auctionitemserver.utils.JsonUtils;
import com.steamedfish.auctionitemserver.utils.LocalDateTimeUtils;
import com.steamedfish.auctionitemserver.utils.TestController;
import jdk.nashorn.internal.parser.JSONParser;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.Asserts;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 高山福
 * @since 2021-03-17
 */
@RestController
@RequestMapping("/auctionitemserver/auctionItem")
public class AuctionItemController {

    private Integer DEFAULT_PAGE_INDEX = 0;

    private Integer DEFAULT_PAGE_SIZE = 10;

    @Autowired
    private AuctionItemService auctionItemService;

    @Autowired
    private AuctionItemImageService auctionItemImageService;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private ElasticSearchService elasticSearchService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    Logger logger = LoggerFactory.getLogger(this.getClass());





    private String dateFormat = "yyyy-MM-dd HH:mm:ss";


    @Transactional
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public ResponseEntity<?> uploadAuctionItem(HttpServletRequest request
                                               , HttpServletResponse response
                                               , @RequestBody AuctionItemModel auctionItemModel
                                               ) {


        //获取用户id
        //获取用户id
//        String userId = data.getUserId();
        String json = SecurityContextHolder.getContext().getAuthentication().getName();
        UserEntiry userEntiry = JSON.parseObject(json, UserEntiry.class);
        String userId = userEntiry.getId();
//        String userId = "user_c2f0e22c-abfa-4369-8724-a71b7029a276";



        AuctionItem auctionItem = new AuctionItem();
        if (auctionItemModel.getAuctionType() == null){
            throw new NullPointerException("拍卖方式不能为空");
        }

        BeanUtils.copyProperties(auctionItemModel,auctionItem);

        //生成基本参数
        String id = "auction_item_" + UUID.randomUUID();
        String status = "0";
        String preTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateFormat));
        LocalDateTime time = parseStringToDateTime(preTime, dateFormat);


        //设置公共部分的参数
        auctionItem.setId(id);
        auctionItem.setCreateTime(time);
        auctionItem.setStatus(status);
        auctionItem.setUserId(userId);


        //单独设置不同拍卖方式部分的参数
        if (auctionItemModel.getAuctionType().equals("0")) {
            auctionItem.setLowerPrice(new BigDecimal(auctionItemModel.getLowerPrice()));
            auctionItem.setPriceStep(new BigDecimal(auctionItemModel.getPriceStep()));
            auctionItem.setAuctionTime(parseStringToDateTime(auctionItemModel.getAuctionTime(),dateFormat));
            auctionItem.setEndTime(parseStringToDateTime(auctionItemModel.getEndTime(),dateFormat));

            auctionItemService.save(auctionItem);
        }else {
            auctionItem.setUpPrice(new BigDecimal(auctionItemModel.getUpPrice()));
            auctionItemService.save(auctionItem);
        }

        if (auctionItemModel.getUrls() != null) {

            List<AuctionItemImage> imageList = new ArrayList<>();
            List<String> urls = Arrays.asList(auctionItemModel.getUrls());


            urls.stream().forEach(e -> {
                AuctionItemImage auctionItemImage = new AuctionItemImage();
                String imageId = "auction_item_image_" + UUID.randomUUID();
                auctionItemImage.setId(imageId);
                auctionItemImage.setItemImageId(auctionItemModel.getItemImageId());
                auctionItemImage.setImage(e);
                imageList.add(auctionItemImage);
            });
            auctionItemImageService.saveBatch(imageList);
        }



        System.out.println(auctionItem.toString());

        //将上传的商品id存放到redis中，以变推广服务中心进行推广。
        try {
            redisTemplate.opsForSet().add("ad-for-auction", id);
        } catch (Exception e) {
            logger.info("无法将新上传商品的id存放到redis，请检查代码");
        }




        return ResponseEntity.ok("上传成功");
    }


    @RequestMapping(value = "/searchbyuser", method = RequestMethod.POST)
    public ResponseEntity<?> searchAuctionItem(HttpServletRequest request
                                               , HttpServletResponse response
                                               , @RequestBody AuctionItemModel data
                                                ) {


        //获取用户id
//        String userId = data.getUserId();
        String json = SecurityContextHolder.getContext().getAuthentication().getName();
        UserEntiry userEntiry = JSON.parseObject(json, UserEntiry.class);
        String userId = userEntiry.getId();

//        userId = id == null ? "user_c2f0e22c-abfa-4369-8724-a71b7029a276" : id;

        //根据用户id查询发布的信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        List<AuctionItem> auctionItems = auctionItemService.list(queryWrapper);

        //根据拍品信息查询图片信息
        List<AuctionItemModel> auctionItemModels = new ArrayList<>();
        auctionItems.forEach(e -> {
            AuctionItemModel auctionItemModel = new AuctionItemModel();
            BeanUtils.copyProperties(e, auctionItemModel);
            auctionItemModel.setLowerPrice(e.getLowerPrice() == null?"-":e.getLowerPrice().toString());
            auctionItemModel.setPriceStep(e.getPriceStep() == null?"-":e.getPriceStep().toEngineeringString());
            auctionItemModel.setUpPrice(e.getUpPrice() == null?"-":e.getUpPrice().toEngineeringString());
            auctionItemModel.setAuctionTime(LocalDateTimeUtils.localDateTimeTOString(e.getAuctionTime(), dateFormat));
            auctionItemModel.setEndTime(LocalDateTimeUtils.localDateTimeTOString(e.getEndTime(), dateFormat));
            auctionItemModel.setCreateTime(LocalDateTimeUtils.localDateTimeTOString(e.getCreateTime(), dateFormat));

            //查询图片信息
            QueryWrapper queryWrapperForImage = new QueryWrapper();
            queryWrapperForImage.eq("item_image_id", e.getItemImageId());
            List<AuctionItemImage> images = auctionItemImageService.list(queryWrapperForImage);

            String[] urlList = new String[images.size()];
            for (int i = 0; i < images.size(); i++) {
                urlList[i] = images.get(i).getImage();
            }
            auctionItemModel.setUrls(urlList);
            auctionItemModels.add(auctionItemModel);
        });

        //返回拍品数据信息
        System.out.println(JsonUtils.toJson(auctionItemModels));


        return ResponseEntity.ok(auctionItemModels);


    }


    @Transactional
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    public ResponseEntity<?> removeAuctionItem(HttpServletRequest request,
                                               HttpServletResponse response,
                                               @RequestBody AuctionItemModel auctionItemModel) {

        //接受拍品id
        String id = auctionItemModel.getId();

        if (!StringUtils.isNotBlank(id) || !StringUtils.isNotEmpty(id)) {
            throw new RuntimeException("删除失败");
        }

        //根据拍品id删除拍品
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", id);
        AuctionItem auctionItem = auctionItemService.getOne(queryWrapper);

        Map removeMap = new HashMap<>();
        removeMap.put("id", id);
        boolean removed = auctionItemService.removeByMap(removeMap);

        //根据图片id删除图片
        Map removeIamgeMap = new HashMap();
        removeIamgeMap.put("item_image_id", auctionItem.getItemImageId());
        auctionItemImageService.removeByMap(removeIamgeMap);


        if (removed == true) {
            return ResponseEntity.ok("删除成功");
        } else {
            return ResponseEntity.ok("删除失败");
        }
    }


    @Transactional
    @RequestMapping(value = "/essearch", method = RequestMethod.POST)
    public ResponseEntity<?> searchByNameOrDescription(HttpServletRequest request,
                                                       HttpServletResponse response,
                                                       @RequestBody AuctionItemModel data) {


        //获取搜索词和分页信息
        String searchString = data.getName();
        String pageIndex = data.getPageIndex();
        String pageSize = data.getPageSize();

        //检测搜索词合法性
        SearchHits<AuctionItemModel> auctionItemModelSearchHits = elasticSearchService.searchByKey(searchString, pageIndex, pageSize);
        System.out.println(auctionItemModelSearchHits);

        //将内容重新封装
        List<AuctionItemModel> auctionItemModels = elasticSearchService.getAuctionItemModelList(auctionItemModelSearchHits);


        //将搜索结果组装然后返回
        return ResponseEntity.ok(auctionItemModels);
    }



    @Transactional
    @RequestMapping(value = "/getes", method = RequestMethod.POST)
    public ResponseEntity<?> searchById(HttpServletRequest request,
                                        HttpServletResponse response,
                                        @RequestBody AuctionItemModel data){
        //判断参数是否存在
        if (data.getId() == null || data.getId().equals("")) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("请求参数不存在");
        }
        AuctionItemModel auctionItemModel = elasticSearchService.getAuctionModelById(data.getId());

        return ResponseEntity.ok(auctionItemModel);
    }




















    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseEntity<?> updateAuctionItem(HttpServletRequest request
                                                , HttpServletResponse response
                                                , @RequestBody AuctionItemModel auctionItemModel
                                                ){
        //获取前端传值
        String itemId = "auction_item_db144ecf-9430-45d2-8bda-36abdcdd4ae8";
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", itemId);
        List<AuctionItemModel> auctionItemModels = TestController.searchAuctionItem(queryWrapper);
        AuctionItemModel auctionItemModel1 = auctionItemModels.get(0);


        //获取用户id


        //获取产品id




        //根据产品id更新产品信息



        //根据图片id更新图片信息

        return null;



    }




    @RequestMapping(value = "/searchitem", method = RequestMethod.POST)
    public ResponseEntity<?> searchItemById(HttpServletRequest request,
                                            HttpServletResponse response,
                                            @RequestParam String id){

        //根据拍品id获取拍品信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",id);
        AuctionItem auctionItem = auctionItemService.getOne(queryWrapper);

        //更具图片id获取图片信息
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("item_image_id", auctionItem.getItemImageId());
        List<AuctionItemImage> auctionItemImages = auctionItemImageService.list(queryWrapper1);



        //拼接
        AuctionItemModel auctionItemModel = new AuctionItemModel();
        BeanUtils.copyProperties(auctionItem, auctionItemModel);
        auctionItemModel.setLowerPrice(auctionItem.getLowerPrice() == null?"-":auctionItem.getLowerPrice().toString());
        auctionItemModel.setPriceStep(auctionItem.getPriceStep() == null?"-":auctionItem.getPriceStep().toEngineeringString());
        auctionItemModel.setUpPrice(auctionItem.getUpPrice() == null?"-":auctionItem.getUpPrice().toEngineeringString());
        auctionItemModel.setAuctionTime(LocalDateTimeUtils.localDateTimeTOString(auctionItem.getAuctionTime(), dateFormat));
        auctionItemModel.setEndTime(LocalDateTimeUtils.localDateTimeTOString(auctionItem.getEndTime(), dateFormat));
        auctionItemModel.setCreateTime(LocalDateTimeUtils.localDateTimeTOString(auctionItem.getCreateTime(), dateFormat));

        String[] urlList = new String[auctionItemImages.size()];
        for (int i = 0; i < auctionItemImages.size(); i++) {
            urlList[i] = auctionItemImages.get(i).getImage();
        }
        auctionItemModel.setUrls(urlList);

        //返回
        return ResponseEntity.ok(auctionItemModel);


    }



    public static LocalDateTime parseStringToDateTime(String time, String format)
    {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.parse(time, df);
    }

}
